package Imp.Controller;

import Imp.Service.ImpService;
import Imp.clients.openFeignlntImp;
import entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

@Slf4j
@RestController
@RequestMapping("/service")

public class ImpServiece {
    @Autowired
    openFeignlntImp openFeignlntImp;
    @Autowired
    ImpService impService;


//    @GetMapping("/get/tm")
//    public Result getTm(@RequestParam(value = "cartid") Integer cartid, @RequestParam(value = "number") int number) {
//        impService.addOrder(number, cartid, "Ok to add order");
//        return new Result("获取成功", 200, null);
//    }

    @GetMapping("/get/first")
    public String getSting(HttpServletRequest request) {
        String token = request.getHeader("token");
        log.info("这是获取的头 :{}", token);
        String itemSum = openFeignlntImp.getItemSum();
        return "this is a service1 to test , this is test output :" + itemSum;
    }

    @GetMapping("/get/second")
    public String getSting2() {
        return "this is a service2 to get";
    }

    @GetMapping("/get/pay")
    public Result PayService(@RequestParam(value = "orderid") int orderId) {
        return impService.PayService(orderId);
    }

    @GetMapping("/get/order")
    public Result getOrder(@RequestParam(value = "userid") Integer userid,
                           @RequestParam(value = "itemid") Integer itemid,
                           @RequestParam(value = "num") Integer num) {
        int orderId;
        try {
             orderId = impService.ToAddOrder(userid, itemid, num);
        } catch (DataAccessException e) {
            SQLException sqlException = (SQLException) e.getCause();
            if (sqlException.getSQLState().equals("HY000")) {
                return new Result("数据库操作失败", 400, "金额不足");
            }
            return new Result("数据库操作失败", 500, "未知错误");

        } catch (Exception e) {
            return new Result("下单操作失败", 400, e.getMessage());
        }

        return new Result("下单操成功", 200, orderId);
    }

}